<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-25 09:40
 * Modified Time: 2019-06-25 09:40
 * Version: 2.0
 */
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

/**
 * Class User 理发师和店长信息基础用户表
 * @package App\Models
 * Author: Happy dong
 * Created Time: 2019-06-25 09:42
 */
class User extends Model implements AuthenticatableContract
{
    use Authenticatable;
	protected $table = 'user';
	protected $guarded = [];

	protected $hidden = [
		'password',
		'updated_at'
	];


	public function picture(){
		return $this->hasOne(Picture::class,'id','portrait');
	}

	public function profilePicture(){
		return $this->hasOne(Picture::class,'id','profile_picture');
	}

	public function profileVideo(){
		return $this->hasOne(Video::class,'id','profile_video');
	}

	public function store(){
		return $this->belongsToMany(Store::class,'user_store', 'uid','sid' )->withPivot('rid', 'is_work','is_default');
	}

	public function userStore(){
		return $this->hasMany(UserStore::class,'uid','id');
	}


	public function scopeStoreBy(Builder $query,$storeId){
		return $query->has('userStore','and',function($q) use($storeId){
			$q->where(['sid'=>$storeId]);
		});
	}

	public function userLike(){
		return $this->hasMany(UserLike::class,'user_id','id');
	}

	public function order(){
		return $this->hasMany(Order::class,'barber_id','id');
	}
	/**
	 * 用户关注的理发师
	 * @param Builder $query
	 * @param $memberId
	 * @return Builder
	 */
	public function scopeUserLikeBy(Builder $query,$memberId){
		return $query->has('userLike','and',function($q) use($memberId){
			$q->where(['member_id'=>$memberId]);
		});
	}
	/**
	 * UserStore 查询
	 * @param Builder $query
	 * @param $role
	 * @param $isWork
	 * @return Builder
	 */
	public function scopeStoreWorkBy(Builder $query, $role,$isWork){
		return $query->has('store','and',function($q) use($role,$isWork){
			$q->where(['rid'=>$role,'is_work'=>$isWork]);
		});
	}

	/**
	 * 获取理发师头像
	 * @param $userId
	 * @return mixed
	 */
	public static function getUsernamePortraitInfoById($userId,$onlyName=false){
		$info = self::where('id',$userId)->with('picture:id,image')->select(['id','nick','portrait'])->first();
		return $onlyName ? $info->nick : $info;
	}
}